<template>
  <div>
    <div class="center-w">
      <el-card
        style="margin-bottom: 10px;"
        shadow="always"
        :body-style="{ padding: '20px' }"
      >
        <div style="display: flex;align-items: center;">
          <span style="font-size: 12px;">用户名：</span>
          <el-input
            placeholder="请输入用户名"
            prefix-icon="el-icon-search"
            v-model="pageparm.name"
            clearable
            size="mini"
            @input="search"
          >
          </el-input>
          <div style="display: flex; align-items: center;">
            <span style="font-size: 12px;">身份：</span>
            <el-select
              size="mini"
              v-model="pageparm.roleId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <div style="display: flex; margin-left: 20px; align-items: center;">
            <span style="font-size: 12px;">标签：</span>
            <el-select
              size="mini"
              v-model="pageparm.labelId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in tagData"
                :key="item.id"
                :label="item.labelName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <el-button
            style="margin-left: 20px;"
            type="primary"
            size="mini"
            @click="search"
            >查询</el-button
          >
          <el-button type="success" size="mini" @click="clearForm"
            >清空</el-button
          >
        </div>
      </el-card>
      <div
        shadow="always"
        style="height: 100%;overflow-y: scroll; padding: 0 5px"
      >
        <el-table
          :header-cell-style="{
            background: '#f3f6fa',
            color: '#555'
          }"
          height="100%"
          size="mini"
          border
          :data="userData"
        >
          <el-table-column
            show-overflow-tooltip
            width="50"
            align="center"
            label="ID"
            prop="id"
          >
          </el-table-column>
          <el-table-column align="center" label="头像">
            <template slot-scope="scope">
              <el-image
                class="head-img"
                :preview-src-list="[scope.row.img]"
                :src="scope.row.img"
              >
                <div slot="error" class="image-slot">
                  <!-- <i class="el-icon-picture-outline"></i> src="https://img1.baidu.com/it/u=4035421571,4160111639&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500" -->
                  <el-image
                    class="head-img"
                    src="https://img2.baidu.com/it/u=3969906574,3231239394&fm=253&fmt=auto&app=138&f=PNG?w=500&h=500"
                  >
                  </el-image>
                </div>
              </el-image>
            </template>
          </el-table-column>

          <el-table-column show-overflow-tooltip align="center" label="用户名">
            <template slot-scope="scope">
              <span>{{ scope.row.wxName || "/" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="roleName" align="center" label="身份">
            <template slot-scope="scope">
              <el-select
                :disabled="!$permission('SetIdentity')"
                size="mini"
                style="width: 100px;"
                v-model="scope.row.roleName"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                  @click.native="checkRole(item.roleName, scope.row, item.id)"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            show-overflow-tooltip
            align="center"
            label="注册时间"
          >
          </el-table-column>
          <el-table-column prop="phone" align="center" label="手机号">
            <template slot-scope="scope">
              <span>{{ scope.row.phone || "/" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="money" align="center" label="消费金额">
            <template slot-scope="scope">
              <span style="color:red">{{ scope.row.money }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="money" align="center" label="余额">
            <template slot-scope="scope">
              <span style="color:green">{{ scope.row.balance }}</span>
            </template>
          </el-table-column>

          <el-table-column
            show-overflow-tooltip
            align="center"
            label="公司名字"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.companyName || "/" }}</span>
            </template>
          </el-table-column>

          <el-table-column
            v-if="$permission('SetControl')"
            prop="roleName"
            align="center"
            label="后台控制"
          >
            <template slot-scope="scope">
              <el-switch
                size=""
                @change="setDefultRole(scope.row)"
                v-model="scope.row.state"
              ></el-switch>
              <span style="margin-left: 10px;">{{
                scope.row.state ? "开" : "关"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="$permission('SetUser')"
            align="center"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button
                type="primary"
                @click="getUserDetail(scope.row)"
                size="mini"
                >详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
      </div>
      <Pagination
        v-bind:child-msg="pageparm"
        @callFather="callFather"
      ></Pagination>
    </div>

    <el-dialog title="用户详情" width="43%" :visible.sync="updateVisible">
      <el-descriptions
        :labelStyle="{ width: '120px' }"
        class="margin-top"
        :column="2"
        border
      >
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user-solid"></i>
            用户头像
          </template>
          <el-image
            title="点击放大"
            :preview-src-list="[userInfo.img]"
            style="width: 40px; height: 40px;"
            :src="userInfo.img"
          >
            <div slot="error" class="image-slot">
              <!-- <i class="el-icon-picture-outline"></i> src="https://img1.baidu.com/it/u=4035421571,4160111639&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500" -->
              <el-image
                class="head-img"
                src="https://img2.baidu.com/it/u=3969906574,3231239394&fm=253&fmt=auto&app=138&f=PNG?w=500&h=500"
              >
              </el-image>
            </div>
          </el-image>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-s-promotio"></i>
            钉钉号
          </template>
          <el-select
            v-model="userInfo.dingDingNumber"
            filterable
            remote
            reserve-keyword
            placeholder="请输入用户微信名"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              v-for="item in dingList"
              :key="item.id"
              :label="item.userId"
              :value="item.userId"
            >
              <div style="display:flex;justify-content:space-between">
                <span>{{ item.userName }}</span>
                <span>{{ item.userId }}</span>
              </div>
            </el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            微信ID
          </template>
          {{ userInfo.wxid }}
          <!-- <el-link
            class="copys-button"
            style="margin-left: 5px; font-size: 12px;"
            size="mini"
            type="primary"
            >复制</el-link
          > -->
          <!-- <span
            class="copys-button el-icon-document-copy"
            style="margin-left: 5px; font-size: 14px; color:#409EFF;"
          ></span> -->
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            用户名
          </template>
          <el-input size="mini" v-model="userInfo.wxName"></el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-alarm-clock"></i>
            注册时间
          </template>
          {{ userInfo.createTime }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-s-custom"></i>
            身份
          </template>
          {{ userInfo.roleName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-sell"></i>
            消费金额
          </template>
          <span style="color: #409EFF;"> {{ userInfo.money }}</span>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-coin"></i>
            余额
          </template>

          <span style="color: #f50404;"> {{ userInfo.balance }}</span>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile"></i>
            名字
          </template>
          <el-input size="mini" v-model="userInfo.name"></el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile-phone"></i>
            手机号
          </template>
          <el-input size="mini" v-model="userInfo.phone" disabled></el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-tickets"></i>
            微信号
          </template>
          <el-input size="mini" v-model="userInfo.wXnumber"></el-input>
        </el-descriptions-item>
        <el-descriptions-item span="2">
          <template slot="label">
            <i class="el-icon-folder"></i>
            公司名字
          </template>
          <el-input size="mini" v-model="userInfo.companyName"></el-input>
        </el-descriptions-item>
        <el-descriptions-item span="2">
          <template slot="label">
            <i class="el-icon-location-outline"></i>
            公司地址
          </template>
          <el-input size="mini" v-model="userInfo.companyAddress"></el-input>
        </el-descriptions-item>
        <el-descriptions-item span="2">
          <template slot="label">
            <i class="el-icon-collection-tag"></i>
            已选标签
          </template>
          <el-tag
            size="small"
            v-for="(item, index) in currntTagList"
            :key="item.id"
            :color="item.labelColor"
            closable
            @close="closeTags(index)"
            style="margin: 5px;"
            :style="{ borderColor: item.labelColor }"
            effect="dark"
          >
            <span> {{ item.labelName }}</span>
          </el-tag>
          <span
            v-if="!currntTagList || currntTagList.length == 0"
            style="color: #409EFF
               ; font-size: 12px;"
            >请在标签池里选择你喜欢的标签。</span
          >
        </el-descriptions-item>
        <el-descriptions-item span="2">
          <template slot="label">
            <i class="el-icon-collection-tag"></i>
            标签池
          </template>
          <el-tag
            size="small"
            v-for="item in tagData"
            :key="item.id"
            :color="item.labelColor"
            style="margin: 5px;"
            :style="{ borderColor: item.labelColor }"
            @click="getTags(item)"
            effect="dark"
          >
            <span> {{ item.labelName }}</span>
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination";

import { getTagList } from "../../api/tag";
import {
  getUserList,
  getUserRoleList,
  updateUserRole,
  getUserInfoById,
  updateUserInfo,
  getDingTalkList
} from "../../api/user";

import Clipboard from "clipboard"; //复制

export default {
  data() {
    return {
      userData: [],
      userInfo: {},
      loading: false,
      userForm: {},
      tags: "",
      updateVisible: false,
      userValue: "",
      pageparm: {
        pageIndex: 1,
        size: 20,
        total: 0,
        name: "",
        roleId: null,
        labelId: null
      },
      options: [],
      tagData: [],
      currntTagList: [],
      dingList: []
    };
  },
  components: {
    Pagination
  },

  created() {
    this._getUserList();
    this._getUserRoleList();
    this.getTagPageList();
  },

  mounted() {
    // //复制链接
    // const clipboard = new Clipboard(".copys-button", {
    //   text: () => this.userInfo.wxid
    // });
    // clipboard.on("success", e => {
    //   this.$message.success("复制成功");
    // });
    // clipboard.on("error", e => {
    //   this.$message.success("复制失败");
    // });
  },

  methods: {
    // 控制是否能在小程序端看见后台
    setDefultRole(y) {
      this.$confirm(
        `确定给当前用户 ${!y.state ? "关闭" : "开启"} 小程序管理后台的权限？`,
        "确认信息",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      )
        .then(() => {
          const params = {
            id: y.id,
            state: y.state
          };
          updateUserRole(params).then(res => {
            if (res.code == 200) {
              this.$message.success("切换成功!");
            } else {
              this.$message.info("切换失败!");
            }
            this._getUserList();
          });
        })
        .catch(action => {
          this.$message.info("已取消");
          this._getUserList();
        });
    },

    // 用户列表模糊查询
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this._getDingTalkList(query);
        }, 200);
      } else {
        this.dingList = [];
      }
    },

    // 获取用户列表数据
    async _getDingTalkList(e) {
      let res = await getDingTalkList(e);
      if (res.code == 200) {
        this.dingList = res.data ? res.data : [];
      } else {
        this.$message.error(res.message);
      }
      this.loading = false;
    },

    // 选择标签
    getTags(t) {
      let index = this.currntTagList.findIndex(v => {
        return v.id == t.id;
      });
      if (index != -1) return this.$message.warning("你已经选过该标签了!");
      this.currntTagList.push(t);
    },

    // 去除已选标签
    closeTags(e) {
      this.currntTagList.splice(e, 1);
    },

    // 获取标签列表
    async getTagPageList() {
      let data = {
        pageIndex: 1,
        size: 999
      };
      let result = await getTagList(data);
      if (result.code == 200 && result.data) {
        const { items } = result.data;
        this.tagData = items;
      } else {
        this.tagData = [];
      }
    },

    //获取用户列表数据
    async _getUserList() {
      let res = await getUserList(this.pageparm);
      if (res.data) {
        const { items, totalCount } = res.data;
        this.pageparm.total = totalCount;
        this.userData = items;
      } else {
        this.userData = [];
      }
    },

    // 提交修改用户详情
    async updateInfo() {
      if (this.currntTagList.length > 0) {
        let ids = this.currntTagList.map(v => {
          return { id: v.id };
        });
        this.userInfo.items = ids;
      }
      this.currntTagList.length = [];
      delete this.userInfo.createTime;
      let res = await updateUserInfo(this.userInfo);
      if (res.code == 200) {
        this.$message.success("编辑成功");
        this.updateVisible = false;
        this._getUserList();
      }
    },

    //清空列表
    clearForm() {
      (this.pageparm = {
        pageIndex: 1,
        size: 10,
        total: 0,
        name: "",
        roleId: null,
        labelId: null
      }),
        this._getUserList();
    },

    // 获取用户详情
    async getUserDetail(row) {
      let res = await getUserInfoById(row.id);
      if (res.code == 200 && res.data) {
        this.userInfo = res.data;
        this.currntTagList = res.data.items || [];
        this.updateVisible = true;
      }
    },

    //获取角色身份列表
    async _getUserRoleList() {
      const { data } = await getUserRoleList();
      if (data) {
        this.options = data;
      }
    },

    //修改用户角色信息
    async checkRole(x, e, roleId) {
      this.$confirm(
        `确定把   【${e.wxName}】  的
        身份改成   【${x}】  吗？`,
        "确认信息",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      )
        .then(async () => {
          let params = {
            id: e.id,
            roleId
          };
          const res = await updateUserRole(params);
          if (res.code == 200) {
            this.$message.success("修改成功");
            this._getUserList(this.pageparm);
          } else {
            this.$message.warning("修改失败");
          }
        })
        .catch(action => {
          this.$message.info("已取消");
          this._getUserList();
        });
    },

    // 分页插件事件
    callFather(parm) {
      this.pageparm.pageIndex = parm.pageIndex;
      this.pageparm.size = parm.size;
      this._getUserList(this.pageparm);
    },

    //搜索
    search() {
      this.pageparm.pageIndex = 1;
      this._getUserList(this.pageparm);
    }
  }
};
</script>

<style scoped>
.center-w {
  display: flex;
  /* align-items: center; */
  flex-direction: column;
  background-color: #fff;
  height: 91vh;
  /*padding: 20px;*/
  /*border: 1px solid #ccc;*/
  /*margin: 20px;*/
}

.center-w .el-input {
  max-width: 200px;
  margin-right: 30px;
}

.title {
  color: rgba(16, 16, 16, 1);
  font-size: 20px;
  margin-bottom: 20px;
}

.head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.head-img {
  /* border-radius: 50%; */
  width: 20px;
  height: 20px;
}
</style>
